<template>
  <view class="indexPage">
    <view class="top-bg"></view>
    <!-- 导航栏 -->
    <s-nav-bar title="素材管理" :background="'transparent'" :titleStyle="{ color: '000', fontWeight: 'bold' }" statusBar back
      :backStyle="{ color: '000' }"></s-nav-bar>

    <!-- 状态筛选 -->
    <view class="tabs">
      <view class="tab-list">
        <view class="item" :class="{ active: filterStatus === '' }" @click="changeStatus('')">全部</view>
        <view class="item" :class="{ active: filterStatus === '0' }" @click="changeStatus('0')">待提交</view>
        <view class="item" :class="{ active: filterStatus === '1' }" @click="changeStatus('1')">已提交</view>
        <view class="item" :class="{ active: filterStatus === '2' }" @click="changeStatus('2')">无需备份</view>
      </view>
    </view>

    <scroll-view class="main-scroll" scroll-y @scrolltolower="reachBottom" refresher-enabled
      :refresher-triggered="refreshing" @refresherrefresh="handleRefresh">
      <view class="material-list">
        <view v-for="(order, index) in processedOrderList" :key="index" class="material-card"
          :class="(order.has_material === '1' || order.has_material === '2') ? 'disabled' : ''">
          <!-- 顶部信息 -->
          <view class="card-header">
            <text class="title">{{ order.customer_name }} - {{ order.type }}</text>
            <view class="status-tag" :class="order.statusClass">
              {{ getStatusText(order.has_material) }}
            </view>
          </view>

          <!-- 主体信息 -->
          <view class="card-body">
            <!-- 日期信息 -->
            <view class="info-line">
              <s-icon name="clock-o" size="16" color="#999"></s-icon>
              <text>{{ formatDate(order.start_date) }} 至 {{ formatDate(order.end_date) }}</text>
            </view>

            <!-- 类型和人员 -->
            <view class="info-line">
              <s-icon name="apps-o" size="16" color="#999"></s-icon>
              <text>{{ order.type }} · {{ order.member_name }}</text>
            </view>

            <!-- 订单编号 -->
            <view class="info-line">
              <s-icon name="bookmark" size="16" color="#999"></s-icon>
              <text> {{ order.status }}</text>
            </view>
          </view>

          <!-- 底部操作按钮 -->
          <view class="card-footer">
            <button class="action-btn" @click="handleMaterial(order)" v-if="order.has_material === '0'">
              上传素材
            </button>
            <button class="action-btn" @click="handleMaterial(order)"
              v-if="order.has_material === '1' || order.has_material === '2'">
              查看素材
            </button>
            <view class="btn-divider" v-if="order.has_material === '0' || order.has_material === '1'"></view>
            <button class="no-backup-btn" @click="setNoBackup(order)"
              v-if="order.has_material === '0' || order.has_material === '1'">
              设为无需备份
            </button>
          </view>

          <view class="finished" v-if="order.has_material === '1' || order.has_material === '2'">
            <view class="text">已完成</view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <s-empty v-if="(!orderList || orderList.length === 0) && !loading && !error"
        src="https://img01.yzcdn.cn/vant/empty-image-default.png" text="暂无素材数据"></s-empty>

      <!-- 加载错误提示 -->
      <view class="error-tips" v-if="error && !loading">
        <text>加载失败，请</text>
        <text class="retry" @click="retryLoad">点击重试</text>
      </view>

      <!-- 加载中提示 -->
      <view class="loading-more" v-if="loading">
        <s-icon name="loading" size="24" color="#999"></s-icon>
        <text>加载中...</text>
      </view>

      <!-- 没有更多提示 -->
      <view class="no-more" v-if="finished && orderList.length > 0">
        <text>没有更多了</text>
      </view>
    </scroll-view>

    <!-- 底部导航 -->
    <v-tabbar :version="version" @tabBarChange="tabBarChange" :tabIndex="1" />
  </view>
</template>

<script>
export default {
  data() {
    return {
      version: "",
      orderList: [], // 订单列表数据
      loading: false, // 加载状态
      finished: false, // 是否加载完成
      refreshing: false, // 是否正在刷新
      error: false, // 是否加载失败
      page: 1, // 当前页码
      pageSize: 10, // 每页数量
      filterStatus: "", // 筛选状态
    };
  },
  computed: {
    processedOrderList() {
      return this.orderList.map(order => {
        return {
          ...order,
          statusClass: this.getStatusClass(order.has_material)
        };
      });
    }
  },
  onLoad() {
    this.loadOrders();
  },
  onShow() {
    this.version = uni.getStorageSync('version')
    this.loadOrders();
  },
  methods: {
    // 获取状态样式类
    getStatusClass(status) {
      switch (status) {
        case "0":
          return "waiting";
        case "1":
          return "submitted";
        case "2":
          return "no-backup";
        default:
          return "";
      }
    },

    // 获取状态文本
    getStatusText(status) {
      switch (status) {
        case "0":
          return "待提交";
        case "1":
          return "已提交";
        case "2":
          return "无需备份";
        default:
          return "";
      }
    },

    reachBottom() {
      this.loadOrders();
    },

    // 加载订单数据
    async loadOrders() {
      if (this.loading || this.finished) return;

      this.loading = true;
      this.error = false;

      try {
        let res = await this.sjuAjax.get("/order/list", {
          page: this.page,
          pageSize: this.pageSize,
          has_material: this.filterStatus,
        });

        this.loading = false;
        this.refreshing = false;

        if (res.code === 200) {
          const data = res.data || {};
          const list = data.list || [];
          const pagination = data.pagination || {};

          if (this.page === 1) {
            this.orderList = list;
          } else {
            this.orderList = [...this.orderList, ...list];
          }
          if (
            list.length < this.pageSize ||
            this.page >= pagination.totalPages
          ) {
            this.finished = true;
          } else {
            this.page++;
          }
        } else {
          this.error = true;
          uni.showToast({
            title: res.msg || "加载失败",
            icon: "none",
          });
        }
      } catch (err) {
        this.loading = false;
        this.refreshing = false;
        this.error = true;
        uni.showToast({
          title: "网络错误，请重试",
          icon: "none",
        });
      }
    },

    // 重试加载
    retryLoad() {
      this.error = false;
      this.loadOrders();
    },

    // 处理下拉刷新
    handleRefresh() {
      this.refreshing = true;
      this.page = 1;
      this.finished = false;
      this.loadOrders();
    },

    // 刷新数据
    refreshOrders() {
      this.page = 1;
      this.finished = false;
      this.orderList = [];
      this.loadOrders();
    },

    // 状态变化
    changeStatus(status) {
      this.filterStatus = status;
      this.refreshOrders();
    },

    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return "";
      return dateStr.split(" ")[0];
    },

    // 处理素材
    handleMaterial(order) {
      uni.navigateTo({
        url: `/pages/material/upload?id=${order.id}`,
      });
    },

    // 设为无需备份
    setNoBackup(order) {
      uni.showModal({
        title: "确认操作",
        content: `确定要将订单 ${order.order_number} 设为无需备份吗？`,
        success: (res) => {
          if (res.confirm) {
            this.sjuAjax.post("/material/noback", { id: order.id }, (res) => {
              if (res.code === 200) {
                uni.showToast({
                  title: "设置成功",
                  icon: "success",
                });
                this.refreshOrders();
              } else {
                uni.showToast({
                  title: res.msg || "设置失败",
                  icon: "none",
                });
              }
            });
          }
        },
      });
    },

    // 底部导航切换
    tabBarChange(url) {
      uni.switchTab({
        url: url,
      });
    },
  },
};
</script>
<style lang="less" scoped>
.indexPage {
  background-color: var(--v-bg);
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
}

.top-bg {
  width: 100%;
  height: 312rpx;
  border-radius: 0 0 24rpx 24rpx;
  background: white;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 0;
}

.tabs {
  position: relative;
  padding: 20rpx 30rpx;
  margin-bottom: 20rpx;

  .tab-list {
    display: flex;
    background-color: var(--v-theme);
    border-radius: 40rpx;
    padding: 4rpx;

    .item {
      flex: 1;
      text-align: center;
      padding: 16rpx 0;
      font-size: 28rpx;
      color: rgb(255, 255, 255);
      border-radius: 36rpx;
      transition: all 0.3s;

      &.active {
        background: rgba(255, 255, 255, 1);
        color: var(--v-theme);
        font-weight: bold;
      }
    }
  }
}

.main-scroll {
  flex-grow: 1;
  height: 0;
  box-sizing: border-box;
  padding-top: 20rpx;
}

.material-list {
  display: flex;
  flex-direction: column;
  padding: 0 30rpx 30rpx;

  .material-card {
    margin-bottom: 20rpx;

    /* 替换 gap: 20rpx */
    &:last-child {
      margin-bottom: 0;
      /* 最后一个元素没有 margin */
    }
  }
}

.material-card {
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: var(--v-shadow);
  padding: 30rpx;
  background: #fff;
  position: relative;

  &.disabled {
    background: #dddee8;

    .action-btn,
    .no-backup-btn {
      background: #136;
    }
  }

  .finished {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
    pointer-events: none;

    .text {
      font-size: 46rpx;
      color: rgba(0, 0, 0, .3);
      border-radius: 12rpx;
      border: rgba(0, 0, 0, .3) 6rpx solid;
      width: 180rpx;
      height: 60rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translateX(-50%) translateY(-50%) rotate(25deg);
    }
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;

  .title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    flex: 1;
  }

  .status-tag {
    padding: 8rpx 20rpx;
    border-radius: 40rpx;
    font-size: 22rpx;
    font-weight: bold;

    &.waiting {
      background-color: #fff3e0;
      color: #ff9800;
    }

    &.submitted {
      background-color: #e8f5e9;
      color: #4caf50;
    }

    &.no-backup {
      background-color: #e3f2fd;
      color: #2196f3;
    }
  }
}

.card-body {
  .info-line {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
    /* 替换 gap: 16rpx */
    font-size: 24rpx;
    color: var(--v-gray);

    s-icon {
      margin-right: 16rpx;
      /* 替换 gap: 16rpx */
    }
  }
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20rpx;
  position: relative;
  padding-top: 20rpx;

  &::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 1rpx;
    background-color: #f5f5f5;
  }

  .action-btn,
  .no-backup-btn {
    flex: 1;
    height: 70rpx;
    line-height: 70rpx;
    font-size: 26rpx;
    border-radius: 0;
    position: relative;
    color: #fff;
    background: var(--v-theme);
    border: none;
    padding: 0;

    &::after {
      content: "";
      position: absolute;
      right: 0;
      top: 15rpx;
      bottom: 15rpx;
      width: 1rpx;
      background-color: #f5f5f5;
    }
  }

  .action-btn {

    color: var(--v-theme);
    background: #fff;
    border: solid 1upx var(--v-theme);
  }

  .no-backup-btn::after {
    display: none;
  }

  .btn-divider {
    width: 1rpx;
    height: 40rpx;
    background-color: #f5f5f5;
    margin: 0 10rpx;
  }
}

.loading-more,
.no-more,
.error-tips {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20rpx 0;
  font-size: 28rpx;
  color: #999;
}

.loading-more {
  s-icon {
    margin-right: 10rpx;
    animation: rotate 1s linear infinite;
  }
}

.error-tips {
  color: #ff6b6b;

  .retry {
    color: var(--v-theme);
    margin-left: 10rpx;
    text-decoration: underline;
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}
</style>